package com.cwj.film.AOP;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cwj.common.domain.WatchRecord;
import com.cwj.common.domain.film;
import com.cwj.common.domain.user;
import com.cwj.common.utils.utils;
import com.cwj.common.vo.film.playSo;
import com.cwj.film.dao.WatchRecordDao;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Aspect
@Component
public class WatchRecordAop {
    @Resource
    private HttpServletRequest request;
    @Resource
    private WatchRecordDao watchRecordDao;
    @Resource
    private com.cwj.film.dao.userDao userDao;
    @Resource
    private com.cwj.film.dao.filmDao filmDao;
    @Resource
    private ServletContext servletContext;
    @Resource
    private ObjectMapper objectMapper;
    @Pointcut("execution(* com.cwj.film.service.inter.play.*(..))")
    private void playPointcut(){}
    @Before("playPointcut()")
    public void logWatchFilm() throws JsonProcessingException {
        WatchRecord watchRecord = new WatchRecord();
        playSo playSo = (com.cwj.common.vo.film.playSo) request.getAttribute("playSo");
        film film = new film();
        BeanUtils.copyProperties(playSo,film);
        Map<String,String> map = objectMapper.readValue(objectMapper.writeValueAsString(film), new TypeReference<>() {});
        List<Object> fid = filmDao.selectObjs(new QueryWrapper<film>().allEq(map).select("fid"));
        watchRecord.setFid(fid!=null&&fid.size()>0? (Integer) fid.get(0) : 0);
        Map<String, String> userByCookie = utils.GetUserByCookie(request.getCookies());
        List<Object> uidList = userDao.selectObjs(new QueryWrapper<user>().allEq(userByCookie).select("uid"));

        watchRecord.setUid( uidList!=null&&uidList.size()>0 ? (Integer)uidList.get(0) : 0);
        watchRecord.setFilmEpisode(playSo.getVideo().contains(servletContext.getAttribute("FilmUrl").toString()) ? playSo.getVideo().substring(servletContext.getAttribute("FilmUrl").toString().length()) : playSo.getVideo());
        watchRecordDao.insert(watchRecord);
    }
}
